<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { i18n } from 'boot/i18n'
import { Notify } from 'quasar'
import api from 'src/api'
import type { MeetingUser, UserRole, UserStatus } from 'src/api/service'

const tc = i18n.global.tc

// 用户数据
const users = ref<MeetingUser[]>([])
const loadingUsers = ref(false)
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0
})

// 筛选
const filterRole = ref<UserRole | 'all'>('all')
const filterStatus = ref<UserStatus | 'all'>('all')
const filterQuery = ref('')
// 搜索条件是否已修改
const filtersChanged = ref(false)

// 获取用户列表
const fetchUsers = async (page = 1, rowsPerPage = pagination.value.rowsPerPage) => {
  loadingUsers.value = true

  interface UserListParams {
    page: number;
    page_size: number;
    role?: UserRole;
    status?: UserStatus;
    search?: string;
  }

  const params: UserListParams = {
    page,
    page_size: rowsPerPage
  }

  // 利用v1.2的新查询参数
  if (filterRole.value !== 'all') {
    params.role = filterRole.value
  }
  if (filterStatus.value !== 'all') {
    params.status = filterStatus.value
  }
  if (filterQuery.value.trim()) {
    params.search = filterQuery.value.trim()
  }

  try {
    const response = await api.service.txMeeting.listMeetingUsers(params)
    users.value = response.data.results || []
    pagination.value.rowsNumber = response.data.count || 0
    pagination.value.page = page
    pagination.value.rowsPerPage = rowsPerPage
    filtersChanged.value = false
  } catch (error) {
    console.error('Error fetching meeting users:', error)
    Notify.create({
      message: tc('获取用户列表失败'),
      type: 'negative',
      icon: 'error',
      position: 'top'
    })
    users.value = []
    pagination.value.rowsNumber = 0
  } finally {
    loadingUsers.value = false
  }
}

// 监听筛选条件变化
watch([filterRole, filterStatus, filterQuery], () => {
  // 设置搜索条件已修改
  filtersChanged.value = true
})

// 搜索用户 - 现在直接调用API重新获取数据
const searchUsers = () => {
  fetchUsers(1, pagination.value.rowsPerPage)
}

// 处理表格请求 (分页)
const handleTableRequest = (props: { pagination: { page: number, rowsPerPage: number } }) => {
  const { page, rowsPerPage } = props.pagination
  fetchUsers(page, rowsPerPage)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUsers()
})

// 修改用户角色
const changingRole = ref<Record<string, boolean>>({})
const changeUserRole = async (userId: string, role: UserRole) => {
  changingRole.value[userId] = true
  try {
    await api.service.txMeeting.setUserRole(userId, role)
    Notify.create({
      message: tc('用户角色修改成功'),
      type: 'positive',
      icon: 'check',
      position: 'top'
    })
    // 更新本地数据
    const userIndex = users.value.findIndex((u: MeetingUser) => u.id === userId)
    if (userIndex !== -1) {
      users.value[userIndex].role = role
    }
  } catch (error) {
    console.error('Error changing user role:', error)
    Notify.create({
      message: tc('修改用户角色失败'),
      type: 'negative',
      icon: 'error',
      position: 'top'
    })
  } finally {
    changingRole.value[userId] = false
  }
}

// 修改用户状态
const changingStatus = ref<Record<string, boolean>>({})
const changeUserStatus = async (userId: string, status: UserStatus) => {
  changingStatus.value[userId] = true
  try {
    await api.service.txMeeting.setUserStatus(userId, status)
    Notify.create({
      message: tc('用户状态修改成功'),
      type: 'positive',
      icon: 'check',
      position: 'top'
    })
    // 更新本地数据
    const userIndex = users.value.findIndex((u: MeetingUser) => u.id === userId)
    if (userIndex !== -1) {
      users.value[userIndex].status = status
    }
  } catch (error) {
    console.error('Error changing user status:', error)
    Notify.create({
      message: tc('修改用户状态失败'),
      type: 'negative',
      icon: 'error',
      position: 'top'
    })
  } finally {
    changingStatus.value[userId] = false
  }
}

// 表格列定义 (修正 align 类型)
const columns = [
  {
    name: 'username',
    label: tc('用户名'),
    field: (row: MeetingUser) => row.user.username,
    align: 'left' as const,
    sortable: true
  },
  {
    name: 'fullname',
    label: tc('姓名'),
    field: (row: MeetingUser) => row.user.fullname,
    align: 'left' as const,
    sortable: true
  },
  {
    name: 'telephone',
    label: tc('电话'),
    field: (row: MeetingUser) => row.user.telephone,
    align: 'left' as const
  },
  {
    name: 'company',
    label: tc('单位'),
    field: (row: MeetingUser) => row.user.company,
    align: 'left' as const,
    sortable: true
  },
  {
    name: 'role',
    label: tc('角色'),
    field: 'role',
    align: 'left' as const
  },
  {
    name: 'status',
    label: tc('状态'),
    field: 'status',
    align: 'left' as const
  }
  // {
  //   name: 'actions',
  //   label: tc('操作'),
  //   field: 'id',
  //   align: 'center' as const
  // }
]
</script>

<template>
  <q-scroll-area style="height: calc(100vh - 50px)">
    <div class="q-pa-md">
      <h5 class="q-mt-none q-mb-md">{{ tc('用户管理') }}</h5>

      <!-- 筛选工具栏 -->
      <div class="q-mb-md q-pa-md filter-container">
        <div class="row q-col-gutter-md items-center">
          <!-- 角色筛选 -->
          <div class="col-12 col-md-3">
            <q-select v-model="filterRole" :options="[
              { label: tc('全部角色'), value: 'all' },
              { label: tc('管理员'), value: 'admin' },
              { label: tc('普通用户'), value: 'regular' }
            ]" emit-value map-options filled dense :label="tc('用户角色')" />
          </div>

          <!-- 状态筛选 -->
          <div class="col-12 col-md-3">
            <q-select v-model="filterStatus" :options="[
              { label: tc('全部状态'), value: 'all' },
              { label: tc('有效'), value: 'active' },
              { label: tc('无效'), value: 'inactive' }
            ]" emit-value map-options filled dense :label="tc('用户状态')" />
          </div>

          <!-- 搜索框 -->
          <div class="col-12 col-md-3">
            <q-input v-model="filterQuery" filled dense :label="tc('搜索用户名/姓名/电话/单位')" clearable>
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
          </div>

          <!-- 搜索按钮 -->
          <div class="col-12 col-md-3">
            <q-btn color="primary" :label="tc('搜索')" icon="search" @click="searchUsers" :loading="loadingUsers" />
          </div>
        </div>
      </div>

      <!-- 搜索条件改变提示 -->
      <q-banner v-if="filtersChanged" class="bg-blue-1 text-blue-9 q-mb-md">
        <template v-slot:avatar>
          <q-icon name="info" color="info" />
        </template>
        {{ tc('搜索条件已更新') }}
      </q-banner>

      <!-- 用户列表 -->
      <div>
        <q-table flat bordered class="user-table" :rows="users" :columns="columns" row-key="id" :pagination="pagination"
          :loading="loadingUsers" @request="handleTableRequest">
          <template v-slot:body-cell-role="props">
            <q-td :props="props">
              <q-toggle :model-value="props.row.role === 'admin'"
                @update:model-value="isAdmin => changeUserRole(props.row.id, isAdmin ? 'admin' : 'regular')"
                :label="props.row.role === 'admin' ? tc('管理员') : tc('普通用户')"
                :color="props.row.role === 'admin' ? 'primary' : 'grey'" :loading="changingRole[props.row.id]"
                :disable="changingRole[props.row.id]" />
            </q-td>
          </template>

          <template v-slot:body-cell-status="props">
            <q-td :props="props">
              <q-toggle :model-value="props.row.status === 'active'"
                @update:model-value="active => changeUserStatus(props.row.id, active ? 'active' : 'inactive')"
                :label="props.row.status === 'active' ? tc('有效') : tc('无效')"
                :color="props.row.status === 'active' ? 'positive' : 'grey'" :loading="changingStatus[props.row.id]"
                :disable="changingStatus[props.row.id]" />
            </q-td>
          </template>

          <template v-slot:body-cell-actions="props">
            <q-td :props="props">
              <!-- 可能有其他操作，如查看详情 -->
            </q-td>
          </template>

        </q-table>
      </div>
    </div>
  </q-scroll-area>
</template>

<style scoped>
.filter-container {
  border: 1px solid #ddd;
  border-radius: 4px;
}

.user-table {
  width: 100%;
}
</style>
